package org.footballmanager.pandafootball.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.system.domain.FootDj;
import org.footballmanager.pandafootball.system.domain.FootPerson;
import org.footballmanager.pandafootball.system.service.FootDjService;
import org.footballmanager.pandafootball.system.service.FootPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Service
public class FootDjServiceImpl extends ServiceImpl<FootDj> implements FootDjService {
	@Autowired
	private FootPersonService footPersonService;

	@Override
	@Transactional
	public int updateNotNull(FootDj t, HttpServletRequest request) {
		//获取所有球员修改初始球员身价,此功能慎用
		processData(t, request);
		log.info("更新球员等级:" + t.toString());
		return super.updateNotNull(t, request);
	}

	@Override
	@Transactional
	public int save(FootDj t, HttpServletRequest request) {
		processData(t, request);
		log.info("新增球员等级:" + t.toString());
		return super.save(t, request);
	}

	private void processData(FootDj t, HttpServletRequest request){
		List<FootPerson> list = footPersonService.getall();
		for(FootPerson fp: list){
			if(fp.getDjId().equals(t.getId()) && (null == fp.getQysj() || "".equals(fp.getQysj()))){
				fp.setQysj(t.getQysj().toString());
				footPersonService.updateNotNull(fp, request);
			}else if(fp.getDjId().equals(t.getId()) && Double.valueOf(fp.getQysj()).equals(t.getQysj())){
				fp.setQysj(t.getQysj().toString());
				footPersonService.updateNotNull(fp, request);
			}
		}
	}

	/**
	 * 根据名称获取等级主键
	 *
	 * @param dj 等级名称
	 * @return 主键
	 */
	@Override
	public Long findByName(String dj) {
		FootDj footDj = this.findByQydj(dj);
		if(footDj != null){
			return footDj.getId();
		}
		return null;
	}

    @Override
    public FootDj findByQydj(String qydj) {
        Example example = new Example(FootDj.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qydj", qydj);
        return this.findByExample(example);
    }
}
